import api from '@/utils/request'

const endpoints = {
    TYPHOON: '/getWeatherData?productType=TYPHOON',
    FORECAST: '/getWeatherData?productType=FORECAST',
    CURRENT_WEATHER: '/getWeatherData?productType=CURRENT_WEATHER',
    WARNING_INFO: '/getWeatherData?productType=WARNING_INFO'
}

/**
 * Fetches raw weather data based on the specified type.
 *
 * @async
 * @function
 * @param {string} type - The type of weather data to fetch (e.g. "TYPHOON", "FORECAST").
 * @returns {Promise<String>} - The fetched weather data.
 * @throws {Error} - Throws an error if the request fails.
 */
const fetchRawData = async type => {
    try {
        const response = await api.get(endpoints[type])
        return await response.data
    } catch (error) {
        throw new Error(error)
    }
}

/**
 * Fetches and parses weather forecast data for the next 5 days.
 *
 * @async
 * @function
 * @returns {Promise<Object>} - The parsed 5-day weather forecast data.
 * @throws {Error} - Throws an error if the data cannot be retrieved or parsed.
 */
const get7DaysWeatherData = async () => {
    try {
        const forecastData = await fetchRawData('FORECAST')
        return JSON.parse(forecastData).filter(v => v['r'] === '440703')[0]
    } catch (error) {
        throw new Error(`Cannot get 7 days weather data: ${error}`)
    }
}

const getData = async () => {
    try {
        const forecastData = await fetchRawData('CURRENT_WEATHER')
        return JSON.parse(forecastData).filter(v => v['n'] === '蓬江')[0]
    } catch (error) {
        throw new Error(`Cannot get days weather data: ${error}`)
    }
}

export {fetchRawData, get7DaysWeatherData,getData}
